package com.jacky.demo.opengl;

import android.opengl.GLES20;
import android.opengl.Matrix;

import java.nio.FloatBuffer;
import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by lixinquan on 2019/2/14.
 */
public class Circle extends Shape {

    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjectMatrix = new float[16];
    private final float[] mViewMatrix = new float[16];
    int mMatrixHandler, mPositionHandle, vColorHandle;

    private FloatBuffer vertexBuffer;
    private float[] circlrCoods;
    float color[] = { 1.0f, 0f, 0f, 1.0f };

    Circle() {
        circlrCoods = createPositions();
        vertexBuffer = GlUtils.allocateFloatBuffer(circlrCoods);
    }

    private float[]  createPositions(){
        ArrayList<Float> data=new ArrayList<>();
        data.add(0.0f);             //设置圆心坐标
        data.add(0.0f);
        data.add(0.0f);

        //分成120条边，绘制出来应该很像圆了
        float radius = 0.5f; //
        float angDegSpan = 360f / 120; //依次递加的角度
        for (float i = 0; i <= 360; i += angDegSpan) {
            data.add((float) (radius * Math.cos(i * Math.PI / 180f))); //x
            data.add((float) (radius * Math.sin(i * Math.PI / 180f))); //y
            data.add(0.0f); //z
        }
        float[] f = new float[data.size()];
        for (int i = 0; i < f.length; i++) {
            f[i] = data.get(i);
        }
        return f;
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
//计算宽高比
        float ratio=(float)width/height;
        //设置透视投影
        Matrix.frustumM(mProjectMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
        //设置相机位置
        Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        //计算变换矩阵
        Matrix.multiplyMM(mMVPMatrix,0,mProjectMatrix,0,mViewMatrix,0);
    }

    @Override
    public void draw() {
        GLES20.glUseProgram(mProgram);
        mMatrixHandler = GLES20.glGetUniformLocation(mProgram, "vMatrix");
        GLES20.glUniformMatrix4fv(mMatrixHandler, 1, false, mMVPMatrix, 0);

        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle,COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 12, vertexBuffer);

        vColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
        GLES20.glUniform4fv(vColorHandle, 1, color, 0);

        int n = 4;//1-绘制圆  2-半圆  3-120度角的扇形  4-1/4圆
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, (circlrCoods.length / 3 / n) + (n>>1));
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }
}
